//
//  XSM3u8Download.m
//  XSDownloadDemo
//
//  Created by 大帅 on 2024/1/4.
//

#import "XSM3u8Download.h"

@interface XSM3u8Download () <MCSAssetExportObserver>
/// 当前下载数据
@property (nonatomic, strong) XSTestModel *model;

@end

@implementation XSM3u8Download

- (instancetype)initWithMedia:(XSTestModel *)model {
    if (self = [super init]) {
        [[SJMediaCacheServer shared] registerExportObserver:self];
        _exporter = [[SJMediaCacheServer shared] exportAssetWithURL:[NSURL URLWithString:model.url]];
        // 这里异步同步进度, 防止阻塞主线程
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self->_exporter synchronize];
        });
        _model = model;
    }
    return self;
}

#pragma mark -- MCSAssetExportObserver
// 下载状态改变
- (void)exporter:(id<MCSAssetExporter>)exporter statusDidChange:(MCSAssetExportStatus)status {
    // 检查是同一个
    if (exporter == _exporter) {
        NSString *statusStr = @"";
        switch (status) {
            case MCSAssetExportStatusUnknown:
                statusStr = @"未知错误";
                break;
                
            case MCSAssetExportStatusWaiting:
                statusStr = @"等待中";
                break;
                
            case MCSAssetExportStatusExporting:
                statusStr = @"下载中";
                break;
                
            case MCSAssetExportStatusFinished:
                statusStr = @"下载完成";
                break;
                
            case MCSAssetExportStatusFailed:
                statusStr = @"下载失败";
                break;
                
            case MCSAssetExportStatusSuspended:
                statusStr = @"暂停中";
                break;
                
            case MCSAssetExportStatusCancelled:
                statusStr = @"取消下载";
                break;
                
            default:
                break;
        }
        NSLog(@"当前下载状态：%@", statusStr);
        
        // 下载状态改变回调
        if (self.delegate && [self.delegate respondsToSelector:@selector(exporter:statusDidChange:mediaModel:)]) {
            [self.delegate exporter:exporter statusDidChange:status mediaModel:self.model];
        }
    }
}

// 下载进度改变
- (void)exporter:(id<MCSAssetExporter>)exporter progressDidChange:(float)progress {
    // 检查是同一个
    if (exporter == _exporter) {        
        // 下载进度改变回调
        if (self.delegate && [self.delegate respondsToSelector:@selector(exporter:progressDidChange:mediaModel:)]) {
            [self.delegate exporter:exporter progressDidChange:progress mediaModel:self.model];
        }
    }
}


-(void)dealloc {
    NSLog(@"dealloc -- %@",self.class);
    [[SJMediaCacheServer shared] removeExportObserver:self];
}

@end
